import { createSlice } from '@reduxjs/toolkit'
import { TOKEN_UTILS } from '@/utils'
import apis from '@/apis'
import CODE from '@/apis/code.config'
const user = createSlice({
  name: 'user',
  initialState: {
    token: TOKEN_UTILS.getToken() || '', // token本地持久化
    userInfo: {},
  },
  reducers: {
    setToken(state: any, action: { payload: any }) {
      state.token = action.payload
      // 保存到本地一份
      TOKEN_UTILS.setToken(action.payload)
    },
    setUserInfo(
      state: { token: string; userInfo: object },
      action: { payload: any }
    ) {
      state.userInfo = action.payload
    },
    clearUserInfo(state: { token: string; userInfo: object }) {
      state.token = ''
      state.userInfo = {}
      TOKEN_UTILS.removeToken()
    },
  },
})
const { setToken, clearUserInfo, setUserInfo } = user.actions
// 登录
function fetchLoginApi(params: any) {
  return async (dispatch: any) => {
    const res = await apis.loginApi(params)
    if (res.data.code === CODE.SUCCESS) {
      dispatch(setToken(res.data.token))
    }
    return res.data
  }
}
// 退出
function fetchLogoutApi() {
  return async (dispatch: any) => {
    dispatch(clearUserInfo())
  }
}
// 获取登录信息
function fetchUerInfoApi() {
  return async (dispatch: any) => {
    try {
      const res = await apis.userInfoApi()
      if (res.data.code === CODE.SUCCESS) {
        dispatch(setUserInfo(res.data.data))
      }
      return res.data
    } catch (error) {}
  }
}
export { fetchLoginApi, fetchLogoutApi, fetchUerInfoApi }
export default user.reducer
